<template>
    <div class="container">
        <div class="header">
            <span class="Data_font">告警列表</span> 
            <div class="header-right">
                <el-dropdown>
                    <span class="user_icon">
                        <img src="../../../../assets/images/user-icon.png">
                    </span>
                    <el-dropdown-menu @click.native='handleUserSetting("loginout")' style="fontSize:12px; top: 65px; left: 1750px;
                    padding: 10px 20px; cursor:pointer">
                        退出登录
                    </el-dropdown-menu>
                </el-dropdown>
                <span class="permission_icon">
                    <img src="../../../../assets/images/permission-icon.png">
                </span>
            </div>
        </div>
        <div class="main">
            <div class="alarm-header">
                <div class="setting-icon el-icon-refresh-left" @click="getAlarmData"></div>  
                <downloadExcel
                  class="download-button"
                  :fields="fileHeader"
                  name="告警信息.xls"         
                  :fetch="getAlarmData"
                  :before-generate="handleExport"
                  >
                  导出
                </downloadExcel>
                <el-button type="info" plain @click="handleOperation('1')" :disabled="unhandledBtnDisabled">待处理</el-button> 
                <el-button type="info" plain @click="handleOperation('2')" :disabled="handledBtnDisabled">已处理</el-button>  
                <el-button type="info" plain @click="handleOperation('3')" :disabled="markBtnDisabled">线下处理</el-button>  
                <el-button type="primary" plain @click="handleOperation('4')" :disabled="ignoreBtnDisabled">屏蔽</el-button>
                <div class="user-selection">
                    <span>告警来源</span>
                    <el-select 
                        v-model="chosenUserOptions" 
                        multiple placeholder="请选择" 
                        :popper-append-to-body="false"
                        @visible-change="userDropdownVisibleChange"
                        @remove-tag="handleCheckboxChange"
                        :disabled="alarmTableList.length == 0 && chosenUserOptions.length == 0"
                        >
                        <el-input 
                          v-model="userInputText" 
                          placeholder="搜索" 
                          class="userinput-style"
                          suffix-icon = "el-icon-search"
                          @input="userSelectInput"
                          >
                        </el-input>
                        <el-checkbox 
                          :indeterminate="isIndeterminate" 
                          v-model="checkAll" 
                          @change="handleCheckAllChange"
                          class="checkAll-style"
                          :disabled="alarmTableList.length == 0"
                        >
                          全选
                        </el-checkbox>
                        <el-checkbox-group v-model="chosenUserOptions" @change="handleCheckboxChange" class="checkbox-style">
                          <el-checkbox v-for="item,index in userList" :label="item" :key="index">{{item}}</el-checkbox>
                        </el-checkbox-group>
                        <el-option 
                          key="1"
                          label=""
                          value="" 
                          style="display:none">
                        </el-option>
                    </el-select>
                </div>
            </div>
            <div class="alarm-area">       
                <span>
                    告警名称
                    <el-dropdown :disabled="alarmTableList.length == 0 && queryData.alarm_name == ''" trigger="click">
                        <span class="el-dropdown-link">
                            <span class="el-dropdown-text">{{alarmNameDefaultValue}}</span>
                            <i class="el-icon-caret-bottom el-icon--right"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown" class="event-dropdown" :appendToBody="false">
                            <el-dropdown-item @click.native="handleAlarmName('所有名称')">所有名称</el-dropdown-item>
                            <el-dropdown-item v-for="(item,index) in alarmNameDropDownList" :key="index"
                             @click.native="handleAlarmName(item)">{{item}}</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </span>
                <span>
                    告警类型
                    <el-dropdown :disabled="alarmTableList.length == 0 && queryData.alarm_type == ''" trigger="click">
                        <span class="el-dropdown-link">
                            <span class="el-dropdown-text">{{alarmTypeDefaultValue}}</span>
                            <i class="el-icon-caret-bottom el-icon--right"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown" class="event-dropdown" :appendToBody="false">
                            <el-dropdown-item @click.native="handleAlarmType('所有类型')">所有类型</el-dropdown-item>
                            <el-dropdown-item v-for="(item,index) in alarmTypeDropDownList" :key="index"
                            @click.native="handleAlarmType(item)">{{item}}</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </span>
                <span>
                    告警级别
                    <el-dropdown :disabled="alarmTableList.length == 0 && queryData.level == ''" trigger="click">
                        <span class="el-dropdown-link">
                            <span class="el-dropdown-text">{{alarmLevelDefaultValue}}</span>
                            <i class="el-icon-caret-bottom el-icon--right"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown" class="event-dropdown" :appendToBody="false">
                            <el-dropdown-item @click.native="handleAlarmLevel('所有级别')">所有级别</el-dropdown-item>
                            <el-dropdown-item v-for="(item,index) in alarmLevelDropDownList" :key="index"
                            @click.native="handleAlarmLevel(item)">{{alarmLevelList[item-1]}}</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </span>
                <span>
                    告警处理状态
                    <el-dropdown :disabled="alarmTableList.length == 0 && queryData.state == ''" trigger="click">
                        <span class="el-dropdown-link">
                            <span class="el-dropdown-text">{{alarmStateDefaultValue}}</span>
                            <i class="el-icon-caret-bottom el-icon--right"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown" class="event-dropdown" :appendToBody="false">
                            <el-dropdown-item @click.native="handleAlarmState('所有状态')">所有状态</el-dropdown-item>
                            <el-dropdown-item v-for="(item,index) in alarmStateDropDownList" :key="index"
                             @click.native="handleAlarmState(item)">{{alarmStateList[item-1]}}</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </span>
                <span class="alarm_time_area">
                    <el-radio-group v-model="alarmTime" @change="handleAlarmTimeChange">
                        <el-radio-button label="今天"></el-radio-button>
                        <el-radio-button label="昨天"></el-radio-button>
                        <el-radio-button label="近3天"></el-radio-button>
                        <el-radio-button label="近7天"></el-radio-button>
                        <el-radio-button label="近30天"></el-radio-button>
                        <el-radio-button label="近半年"></el-radio-button>
                    </el-radio-group>
                </span>
            </div>
            <!-- 表格区域 -->
            <el-table
                tooltip-effect="dark"
                :header-cell-style="{
                    color: '#131416', fontsize: '12px',
                    fontWeight: 'Bold', fontFamily:'Microsoft YaHei, Microsoft YaHei-Bold',
                    backgroundColor:'#F8F8F8',height:'40px' }"
                :row-style="{'height':'54px'}"
                :data="alarmTableList"
                v-loading="loading"
                style="margin-top:20px; margin-bottom: 30px;border: 1px solid #e6e6e6; border-radius: 2px;"
                @selection-change="handleSelectionChange"
                >
                <el-table-column
                    type="selection"
                    width="40">
                </el-table-column>
                <el-table-column
                    prop="alarm_name"
                    label="告警名称"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="alarm_type"
                    label="告警类型"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="level"
                    label="告警等级"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span>{{alarmLevelList[scope.row.level-1]}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="alarm_source"
                    label="告警来源"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="status"
                    label="告警处理状态"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span>{{alarmStateList[scope.row.state-1]}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="last_operate_time"
                    label="最后操作时间"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span>{{scope.row.last_operate_time | dataFormat('YYYY/MM/DD  HH:mm:ss')}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="detail"
                    label="告警详情"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span style="cursor:pointer;color:#0a4cee" @click="showAlarmDetail(scope.row.detail)">查看详情</span>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryData.page"
                :page-sizes="[10, 50, 100, 150, 200]"
                :page-size="queryData.page_size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalCount"
                v-if="totalCount > 0"
                >
            </el-pagination>
        </div> 

        <el-dialog
            title="查看详情"
            :visible.sync="alarmDetailDialogVisible"
            width="35%"
            ref="alarmDialogDetail"
            >
            <pre class="alarm_detail">{{alarmDetails}}</pre>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" plain @click="alarmDetailDialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import moment from 'moment'
export default {
    data() {
        return {
            alarmTableList: [],
            alarmAllList: {},
            totalCount: 0,
            loading: false,
            alarmNameDefaultValue: '所有名称',
            alarmTypeDefaultValue: '所有类型',
            alarmLevelDefaultValue: '所有级别',
            alarmStateDefaultValue: '所有状态',
            alarmNameDropDownList: [],
            alarmTypeDropDownList: [],
            alarmLevelList: ['紧急','重要','次要','提示'],
            alarmLevelDropDownList: [],
            alarmStateList: ['待处理','已处理','线下处理','屏蔽'],
            alarmStateDropDownList: [],
            alarmTime: '今天',
            multipleSelection: [],
            alarmInputBox: '',
            alarmDetailDialogVisible: false,
            highRiskData: false,
            alarmDetails: '',
            ignoreBtnDisabled: false,
            markBtnDisabled: false,
            handledBtnDisabled: false,
            unhandledBtnDisabled: false,
            queryData: {
                'page': 1,'page_size': 10,'level': '','alarm_name': '','alarm_type': '','state': '','last_operate_time' : ['',''],'alarm_source': '',
            },
            downloadClickedFlag: false,
            fileList:[],
            fileHeader:{
                '告警名称': 'alarm_name',
                '告警类型': 'alarm_type',
                '告警来源': 'alarm_source',
                '告警状态': 'state',
                '告警等级': 'level',
                '最后操作时间': 'last_operate_time',
                '告警详情': 'detail'
            },
            chosenUserOptions: [],
            userList:[],
            userListOptions:[],
            checkAll: false,
            userInputText: '',
        }
    },
    created() {
        this.highRiskData = this.$route.params.showHighRiskData;
        if (this.highRiskData) {
            this.alarmLevelDefaultValue = '紧急';
            this.alarmStateDefaultValue = '待处理'
            this.queryData.level = 1;
            this.queryData.state = 1;
        } else {
            this.alarmLevelDefaultValue = '所有级别';
        }
        this.handleAlarmTimeChange('今天');
    },
    methods: {
        // 退出登录
        handleUserSetting(command) {
            if (command === 'loginout') {
                this.$url.post('logout')
                .then(res => {
                    if (res.status === 200) {
                        this.$message.success('退出成功')
                        this.$router.push({ path:'/Login'})
                        this.$stor.del('X-CSRFToken')
                    }
                })
            }
        },
        //  导出操作    
        handleExport() {
            this.downloadClickedFlag = true;
        },
        async getAlarmData() {
            this.loading = true;
            let tempPage = this.queryData.page;
            let tempPageSize = this.queryData.pageSize;
            if(this.downloadClickedFlag){
                this.loading = false;
                this.queryData.page = 1;
                this.queryData['page_size'] =this.totalCount;
            }
            let query = this.queryJoint(this.queryData);
            let res = await this.$url.get(`/trace/alarm?${query}`)
            this.alarmAllList = res.data.data;
            this.loading = false;
            if(this.downloadClickedFlag){
                this.queryData.page = tempPage;
                this.queryData.pageSize = tempPageSize;
                this.fileList = this.alarmAllList.data_list;
                this.fileList.forEach(item => {
                    item.level = this.alarmLevelList[item.level-1];
                    item.state = this.alarmStateList[item.state-1];
                    item.detail = JSON.stringify(item.detail)
                })
                this.downloadClickedFlag = false;
                return this.fileList
            }else {
                this.alarmTableList = this.alarmAllList.data_list; 
                this.totalCount = this.alarmAllList.count;
                if(this.alarmAllList.union_field_values) {
                    let dropdownData = this.alarmAllList.union_field_values;
                    this.alarmNameDropDownList = dropdownData.alarm_name;
                    this.alarmTypeDropDownList = dropdownData.alarm_type;
                    this.alarmLevelDropDownList = dropdownData.level;
                    this.alarmStateDropDownList = dropdownData.state;
                    this.userList = dropdownData.alarm_source;
                    this.userListOptions = dropdownData.alarm_source;
                }
            }
        },
        handleAlarmName(item) {
            this.alarmNameDefaultValue = item;
            this.queryData.page = 1;
            if (item === '所有名称') {
                Object.assign(this.queryData, {'alarm_name':''})
                this.getAlarmData()
            } else {
                Object.assign(this.queryData, {'alarm_name':'item'})
                this.getAlarmData()
            }
        },
        handleAlarmType(item) {
            this.alarmTypeDefaultValue = item;
            this.queryData.page = 1;
            if (item === '所有类型') {
                Object.assign(this.queryData, {'alarm_type':''})
                this.getAlarmData()
            } else {
                Object.assign(this.queryData, {'alarm_type':'item'})
                this.getAlarmData()
            }
        },
        handleAlarmLevel(item) {
            this.queryData.page = 1;
            if (item === '所有级别') {
                this.alarmLevelDefaultValue = '所有级别'
                this.queryData.level = '';
                this.getAlarmData()
            } else {
                this.alarmLevelDefaultValue = this.alarmLevelList[item-1];
                this.queryData.level = item;
                this.getAlarmData()
            } 
        },
        handleAlarmState(item) {
            this.queryData.page = 1;
            if (item === '所有状态') {
                this.alarmStateDefaultValue = '所有状态';
                this.queryData.state = '';
                this.getAlarmData()
            } else {
                this.alarmStateDefaultValue = this.alarmStateList[item-1];
                this.queryData.state = item;
                this.getAlarmData()
            } 
        },
        handleAlarmTimeChange(time) {
            let now = new Date();
            let past = moment(now);
            switch(time){
                case '今天':
                    break;
                case '昨天':
                    past = past.subtract(1,'days');
                    now = moment(now).subtract(1,'days');
                    break;
                case '近3天':
                    past = past.subtract(2,'days');
                    break;
                case '近7天':
                    past = past.subtract(6,'days');
                    break;
                case '近30天':
                    past = past.subtract(29,'days');
                    break;
                case '近半年':
                    past = past.subtract(6,'month');
                    break;         
            }
            let startTime = past.format('YYYY-MM-DD 00:00:00');
            let endTime = moment(now).format('YYYY-MM-DD 23:59:59');
            this.queryData.last_operate_time[0] = startTime;
            this.queryData.last_operate_time[1] = endTime;
            this.queryData.page = 1;
            this.getAlarmData(); 
        },
        // 多选按钮变化
        handleSelectionChange(val) {
            this.multipleSelection = val;
            this.ignoreBtnDisabled = false;
            this.markBtnDisabled = false;
            this.handledBtnDisabled = false;
            this.unhandledBtnDisabled = false;
            val.forEach(item=>{
                if(item.state == 4 || item.state == 2){
                    this.ignoreBtnDisabled = true;
                    this.markBtnDisabled = true;
                    this.handledBtnDisabled = true;
                }else if(item.state == 3){
                    this.markBtnDisabled = true;
                    this.unhandledBtnDisabled = true;
                }else if(item.state == 1) {
                    this.unhandledBtnDisabled = true;
                }
            })
        },
        // 点击按钮
        handleOperation(state) {
            if(this.multipleSelection.length == 0){
                return this.$message.error('请至少选择一项');
            }else {
                let idList = [];
                this.multipleSelection.forEach(item=>{
                    idList.push(item.id);
                })
                this.$url.put('/trace/alarm',{
                    ids: idList.join(','),
                    state: state
                })
                .then(res=>{
                    if(res.status == 200){
                        this.$message.success('操作成功');
                        this.getAlarmData();
                    }
                })
            }
        },
        handleSizeChange(val) {
            Object.assign(this.queryData, {'page_size':val})
            this.queryData.pageSize = val;
            this.getAlarmData()
        },
        handleCurrentChange(val) {
            this.queryData.page = val;
            this.getAlarmData()
        },
        showAlarmDetail(detail) {
            this.alarmDetails = detail;
            this.alarmDetailDialogVisible = true;
            this.$nextTick(() => {
                this.$refs.alarmDialogDetail.$el.scrollTop = 0;
            });
        },
        userDropdownVisibleChange(flag) {
            if (flag == false) {
              this.userInputText = '';
              this.userList = this.userListOptions;
            }
        },
        // 操作用户输入事件
        userSelectInput(content) {
          this.userList = this.userListOptions;
          this.checkAll = false;
          this.isIndeterminateFlag = false;
          if (content !== '') {
            let len = content.length;
            this.checkAll = true;
            this.userList = this.userList.filter(item=>{
              if (item.slice(0,len) == content) {
                if (!this.chosenUserOptions.includes(item)) {
                  this.checkAll = false;
                } else {
                  this.isIndeterminateFlag = true;
                }
                }
                  return item;
            })
          }else if(this.userList.length == this.chosenUserOptions.length){
            this.checkAll = true;
          }
          if (this.userList.length == 0) {
            this.checkAll = false;
          }
        },
        // 操作用户选项全选事件
        handleCheckAllChange(val) {
          if (val) {
            this.checkAll = true;
            this.userList.forEach(item=>{
              if (!this.chosenUserOptions.includes(item)) {
                this.chosenUserOptions.push(item);
              }
            })
          } else {
            this.checkAll = false;
            this.chosenUserOptions = this.chosenUserOptions.filter(item=>{
              return !this.userList.includes(item);
            })
          }
          this.queryData.page = 1;
          Object.assign(this.queryData, {'alarm_source':' this.chosenUserOptions'})
          this.getAlarmData();
        },
        // 操作用户选项改变事件 
        handleCheckboxChange(value) {
          this.isIndeterminateFlag = false;
          this.checkAll = true;
          for (let i = 0;i < this.userList.length; i++) {
            if (!this.chosenUserOptions.includes(this.userList[i])) {
              this.checkAll = false;
            } else {
              this.isIndeterminateFlag = true;
            }
          }
          if (this.userList.length == 0) {
            this.checkAll = false;
          }
          this.queryData.page = 1;
          Object.assign(this.queryData, {'alarm_source':' this.chosenUserOptions'})
          this.getAlarmData();
        },
    },
    computed: {
        isIndeterminate() {
          if(this.chosenUserOptions.length > 0 && this.isIndeterminateFlag) {
            if(this.chosenUserOptions.length < this.userList.length  || !this.checkAll){
              return true;
            }
            return false 
          }
          return false;
        },
  },
}
</script>

<style lang="less" src="../../../../assets/css/anonymizeDataPageStyle.less">
</style>
<style lang="less">
.alarm-header {
    .el-button, .download-button{
        float: right;
        height: 28px;
        padding: 0 27px;
        line-height: 26px;
        margin-right: 6px;
        margin-left: 10px;
    }
    .download-button {
        box-sizing: border-box;
        font-size: 12px;
        border: 1px solid #e6e6e6;
        border-radius: 2px;
        cursor: pointer;
        margin-left: 10px;
        &:hover {
          box-shadow: 0 2px 8px 0 rgba(230, 230, 230, .5);
        }
    }
    .setting-icon {
        box-sizing: border-box;
        cursor: pointer;
        width: 28px;
        height: 28px;
        border: 1px solid #E6E6E6;
        border-radius: 2px;
        text-align: center;
        margin-left: 10px;
        line-height: 26px;
        vertical-align: bottom;
        float: right;
        &::before {
          font-size: 16px;
        }
    }
    .user-selection {
        vertical-align: middle;
        display: inline-block;
        span {
          line-height: 30px;
          font-size: 12px;
        }
        .el-select {
            margin-left: 12px;
            min-width: 332px;
            
            .el-input__inner {
              height: 28px;
              font-size: 12px;
              border-radius: 2px;
              border-color: #E0E2E9;
            }
            .el-input__icon {
              line-height: 30px;
            }
            .el-icon-arrow-up:before {
              color: #a1a1a1;
              content: "\e78f";;
            }
            .el-popper .popper__arrow{
              border-width: 0;
              &::after {
                border-width: 0;
              }
            }
            .el-select-dropdown {
              border-radius: 2px;
            }
            .el-select-dropdown__list {
              padding-top: 3px;
            }
            .userinput-style .el-input__inner {
              border: none;
              border-bottom: 1px solid #e8eaef;
              cursor: text;
            }
            .el-input.is-disabled .el-input__inner {
              background-color: #f8f8f8;
            }
            .checkAll-style,
            .checkbox-style .el-checkbox {
              display: block;
              box-sizing: border-box;
              padding-left: 15px;
              height: 30px;
              line-height: 30px;
              width: 100%;
              &:hover {
                background-color: #eee;
              }
              .el-checkbox__label {
                font-size: 12px;
              }
              .el-checkbox__inner {
                width: 12px;
                height: 12px;
                &::after {
                  width: 6px;
                  height: 6px;
                }
                &::before {
                  top: 4px;
                }
              }
            }
      }
    }  
}   
.alarm-area {
    margin-top: 20px;
    height: 28px;
    line-height: 26px;
    font-family: Microsoft YaHei, Microsoft YaHei-Normal;
    font-weight: Normal;
    font-size: 12px;
    color: #131416;
    .el-dropdown {
        width: 120px;
        height: 28px;
        box-sizing: border-box;
        border: 1px solid #E0E2E9;
        border-radius: 2px;
        font-size: 12px;
        margin-left: 8px;
        margin-right: 30px;
        padding: 0 6px 0 10px;
        cursor: pointer;
        &[aria-disabled] {
            background-color: #f8f8f8;
        }
        .el-dropdown-link {
            width: 100%;
            display: inline-block;
            .el-dropdown-text {
                width: 75px;
                display: inline-block;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                vertical-align: top;
            }
            .el-icon--right {
                height: 28px;
                line-height: 26px;
                float: right;
                font-size: 14px;
                color: #a1a1a1;
            }
        }
        .event-dropdown {
            min-width: 120px;
        }
    }
    .alarm_time_area {
        padding-left: 9px;
        float: right;
        .el-radio-group {
            height: 26px;
            border: 1px solid #E0E2E9; 
            vertical-align: baseline;
            .el-radio-button {
                height: 26px;
            }
        }
        .el-radio-button__inner {
            height: 26px;
            padding: 0 24px !important;
            font-size: 12px;
            font-family: Microsoft YaHei, Microsoft YaHei-Normal;
            font-weight: Normal;
            color: #131416;
            line-height: 24px;
            border-color: #fff;
            border-left: 1px solid #E6E6E6;
            vertical-align: baseline;
            &:hover {
                border-color: #0a4cee;
                color: #0a4cee;
                border-radius: 2px;
            }
        }
        .el-radio-button:first-child .el-radio-button__inner {
            border-color: #fff;
            &:hover {
                border-radius: 2px;
                border-color: #0a4cee;
                color: #0a4cee
            }
        }  
        .el-radio-button__orig-radio:checked+.el-radio-button__inner {
            border-radius: 2px;      
            color: #0a4cee;
            background-color: #fff;
            border-color: #0a4cee;
            box-shadow: none;
            &:hover {
                color: #0a4cee;
            }
        }
        .el-radio-button:last-child .el-radio-button__inner {
            border-radius: 2px;
        }
        .el-radio-button:focus:not(.is-focus):not(:active):not(.is-disabled) {
            box-shadow: none;
        }
    }
}
.alarm_detail {
    font-family: Microsoft YaHei;
    margin: 20px 5px 50px;
    white-space: pre-wrap;
    word-wrap: break-word;
}
.dialog-footer {
    .el-button {
        width: 320px;
    }
}
</style>